<?php


namespace App\Service\Cooperative;


use App\Constants\ErrorCode;
use App\Dao\TaskTagDao;
use App\Exception\BusinessException;
use App\Model\TaskTag;
use Hyperf\Database\Model\Collection;
use Hyperf\Di\Annotation\Inject;

class TaskTagService extends BaseService
{

    /**
     * @Inject()
     * @var TaskTagDao
     */
    protected $taskTagDao;

    /**
     * @return Collection
     */
    public function index(): Collection
    {
        return $this->taskTagDao->where(['cooperative_id' => $this->user()->cooperative_id])->get();
    }

    /**
     * @param $id
     * @param array $data
     * @throws BusinessException
     * @return TaskTag
     */
    public function save($id, array $data)
    {
        if ($id) {
            /** @var TaskTag $tag */
            $tag = $this->taskTagDao->first(['cooperative_id' => $this->user()->cooperative_id, 'id' => $id]);
            if (!$tag) {
                throw new BusinessException(ErrorCode::COOPERATIVE_TAG_NOT_FOUND);
            }
        } else {
            $tag = new TaskTag();
            $tag->cooperative_id = $this->user()->cooperative_id;
        }
        $tag->fill($data);
        $tag->save();
        return $tag;
    }

    /**
     * @param int $id
     * @throws BusinessException
     */
    public function delete(int $id)
    {
        $tag = $this->taskTagDao->first(['cooperative_id' => $this->user()->cooperative_id, 'id' => $id]);
        if(!$tag){
            throw new BusinessException(ErrorCode::COOPERATIVE_TAG_NOT_FOUND);
        }
        $tag->delete();
    }
}